package com.huan.study.excel.util;

import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.Objects;

/**
 * excel 工具类
 *
 * @author huan.fu
 * @date 2023/3/21 - 20:25
 */
public class ExcelUtil {

    /**
     * 合并指定Excel sheet页、指定列中连续相同内容的单元格
     *
     * @param sheet    Excel sheet
     * @param startRow 从第几行开始， startRow的值从1开始
     * @param column   指定列
     */
    public static void mergeSameCellContentColumn(Sheet sheet, int startRow, int column) {
        int totalRows = sheet.getLastRowNum();
        int firstRow = 0;
        int lastRow = 0;
        // 上一次比较是否相同
        boolean isPrevCompareSame = false;
        String prevMergeAddress = null;
        String currentMergeAddress;
        // 从第几开始判断是否相同
        if (totalRows >= startRow) {
            for (int i = startRow; i <= totalRows; i++) {
                String lastRowCellContent = sheet.getRow(i - 1).getCell(column).getStringCellValue();
                String curRowCellContent = sheet.getRow(i).getCell(column).getStringCellValue();
                if (curRowCellContent.equals(lastRowCellContent)) {
                    if (!isPrevCompareSame) {
                        firstRow = i - 1;
                    }
                    lastRow = i;
                    isPrevCompareSame = true;
                } else {
                    isPrevCompareSame = false;
                    currentMergeAddress = firstRow + lastRow + column + column + "";
                    if (lastRow > firstRow && !Objects.equals(currentMergeAddress, prevMergeAddress)) {
                        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, column, column));
                        prevMergeAddress = currentMergeAddress;
                    }
                }
                // 最后一行时判断是否有需要合并的行
                if ((i == totalRows) && (lastRow > firstRow)) {
                    currentMergeAddress = firstRow + lastRow + column + column + "";
                    if (!Objects.equals(currentMergeAddress, prevMergeAddress)) {
                        sheet.addMergedRegion(new CellRangeAddress(firstRow, lastRow, column, column));
                    }
                }
            }
        }
    }
}
